import java.security.MessageDigest; 

/**
 * This is an implementation of a SHA-1 hash. If you want to know more
 * about how it works, check out Wikipedia (although I consider it 
 * to be fairly worthless in this case, unfortunately).
 * 
 * @author zach
 *
 */
public class SHA1Hash implements HashFunction<String>{ 

	public SHA1Hash(){

	}
	
	private static String convertToHex(byte[] data) { 
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) { 
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do { 
				if ((0 <= halfbyte) && (halfbyte <= 9)) 
					buf.append((char) ('0' + halfbyte));
				else 
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while(two_halfs++ < 1);
		} 
		return buf.toString();
	}

	public int hash(String key) { 
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("SHA-1");

			byte[] sha1hash = new byte[40];
			md.update(key.getBytes("iso-8859-1"), 0, key.length());

			sha1hash = md.digest();

			String hexString = convertToHex(sha1hash);
			return Integer.parseInt(hexString.substring(hexString.length()-7,hexString.length()), 16);
		}
		catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	} 
}

